package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.base.mapper.UserMapper;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQueryObject;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        TablePageInfo<CarPackageAudit> page = new TablePageInfo<>(carPackageAuditMapper.selectForList(qo));
        for (CarPackageAudit row : page.getRows()) {
            Long serviceItemId = row.getServiceItemId();
            ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(serviceItemId);
            row.setServiceItem(serviceItem);

            Long auditorId = row.getAuditorId();
            User auditor = userMapper.selectByPrimaryKey(auditorId);
            row.setAuditor(auditor);

        }
        return page;
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImageById(Long id) {
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(audit.getBpmninfoId());
        if (bpmnInfo == null) {
            throw new BusinessException("流程定义已删除, 无法查看");
        }
        if (audit.getStatus() == CarPackageAudit.STATUS_IN_ROGRESS) {
            Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
            //激活的activiti数组,  也就是高亮的数组
            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());

            BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            InputStream inputStream = generator.generateDiagram(
                    bpmnModel,
                    activeActivityIds,
                    Collections.emptyList(),
                    "宋体",
                    "宋体",
                    "宋体"
            );
            return inputStream;
        } else {
            BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            InputStream inputStream = generator.generateDiagram(
                    bpmnModel,
                    Collections.emptyList(),
                    Collections.emptyList(),
                    "宋体",
                    "宋体",
                    "宋体"
            );
            return inputStream;
        }

    }


    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        carPackageAuditMapper.changeAuditStatus(id, CarPackageAudit.STATUS_CANCEL);
        serviceItemMapper.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "用户撤销申请");
    }

    @Override
    public void audit(Long id, int auditStatus, String info) {
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        //整理审批意见
        User user = ShiroUtils.getUser();
        String userName = user.getUserName();
        String commentStr = auditStatus == 2 ? "【" + userName + " 同意】" : "【" + userName + " 拒绝】";
        info += commentStr;
        audit.setInfo((audit.getInfo()+"<br>"+info));
        audit.setAuditTime(new Date());
        //activiti审批任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(audit.getInstanceId())
                .singleResult();
        //添加审批意见
        taskService.addComment(task.getId(), audit.getInstanceId(), info);

        taskService.setVariable(task.getId(), "auditStatus", auditStatus);
        //完成任务
        taskService.complete(task.getId());
        //获取下一个任务
        Task nextTask = taskService.createTaskQuery()
                .processInstanceId(audit.getInstanceId())
                .singleResult();
        if (auditStatus==2) {   //审核通过情况
            if (nextTask == null) {
                //整个通过了
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                serviceItemMapper.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }else {
                String assignee = nextTask.getAssignee();
                Long auditorId = Long.valueOf(assignee);
                audit.setAuditorId(auditorId);
            }
        }else {  //第一个任务审核拒绝情况
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            serviceItemMapper.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);

        }
        carPackageAuditMapper.updateByPrimaryKey(audit);

    }

}
